package com.yjy.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.yjy.common.Result;
import com.yjy.entity.Category;
import com.yjy.entity.Introduction;
import com.yjy.entity.User;
import com.yjy.service.CategoryService;
import com.yjy.service.IntroductionService;
import com.yjy.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/echarts")
public class EchartsController {

    @Resource
    public CategoryService categoryService;

    @Resource
    public IntroductionService introductionService;

    @Resource
    public UserService userService;

    @GetMapping("/pie")
    public Result pie() {
        List<Map<String,Object>>list = new ArrayList<>();
        //思路： 查询出不同的分类信息
        List<Category> categories = categoryService.selectAll(new Category());
        //根据不同分类查询有多少篇文章
        // 查询出所有的帖子信息
        List<Introduction> introductions = introductionService.selectAll(new Introduction());
        for (Category category : categories) {
            long count = introductions.stream().filter(x -> category.getId().equals(x.getCategoryId())).count();//category.getId()是为了防止后面哪个为空
            Map<String,Object> map = new HashMap<>();
            map.put("name",category.getTitle());
            map.put("value",count);
            list.add(map);
        }
        return Result.success(list);
    }

    @GetMapping("/bar")
    public Result bar() {
        Map<String,Object>resultMap = new HashMap<>();
        List<String>xList = new ArrayList<>();
        List<Long>yList = new ArrayList<>();
        Map<String,Long> map = new HashMap<>();

        // 查询所有的用户
        List<User>users = userService.selectAll(new User());
        // 查询出所有的帖子信息
        List<Introduction>introductions = introductionService.selectAll(new Introduction());
        for (User user : users) {
            long count = introductions.stream().filter(x -> user.getId().equals(x.getUserId())).count();
//            xList.add(user.getName());
//            yList.add(count);
            map.put(user.getName(),count);

        }
        //对map进行排序,按照value
        LinkedHashMap<String, Long> sortedMap = map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

        for (String key : sortedMap.keySet()) {
            xList.add(key);
            yList.add(sortedMap.get(key));
        }

        //top 几的问题 截断一下
        if(xList.size()>5 && yList.size()>5){
            xList = xList.subList(0,5);
            yList = yList.subList(0,5);
        }



        resultMap.put("xAxis",xList);
        resultMap.put("yAxis",yList);
        return Result.success(resultMap);
    }

    @GetMapping("/line")
    public Result line() {
        Map<String,Object>resultMap = new HashMap<>();
        List<Long>yList = new ArrayList<>();
        // 获取最近多少天的年月日list  这个可以复用
        Date today = new Date();
        DateTime start = DateUtil.offsetDay(today, -7);
        List<String> xList = DateUtil.rangeToList(start, today, DateField.DAY_OF_YEAR).stream().map(DateUtil::formatDate).toList();

        //把所有的帖子查出来
        List<Introduction> introductions = introductionService.selectAll(new Introduction());
        for (String day : xList) {
            long count = introductions.stream().filter(x -> ObjectUtil.isNotEmpty(x.getTime()) && x.getTime().contains(day)).count();
            yList.add(count);
        }
//        x.getTime().contains(day) 的作用是 筛选出时间字段（time）中包含指定日期（day）的帖子记录 ，从而统计某一天的帖子数量。具体解释如下：
        //潜在问题
        //格式一致性 ：如果 getTime() 返回的时间格式与 day 的格式不一致（例如 getTime() 返回 "05/10/2023"，而 day 是 "2023-10-05"），contains 会失效。
        //误判风险 ：如果 day 是 "10"，而 getTime() 返回 "2023-10-05"，contains 会匹配到月份部分，导致逻辑错误。
        resultMap.put("xAxis",xList);
        resultMap.put("yAxis",yList);
        return Result.success(resultMap);
    }

}
















